
package com.nassir.chatroom.socket;

import java.net.InetSocketAddress;
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nassir.chatroom.util.SystemExit;


/**
 * Socket client
 * @author nassir.wen
 * @date 2012-12-7下午4:30:55
 * @Copyright: Copyright (c) 2012
 */
public class SocketClient {
    private Log log = LogFactory.getLog(this.getClass());

    private int reconCount = 0;
    private int port;
    private String host;
    
    private Socket client;

    /**
     * constructor of SocketClient
     * 
     * @param host
     * @param port
     * @param srcComponentID
     * @throws Exception
     */
    public SocketClient(String host, int port) {
        this.host = host;
        this.port = port;
        try {
            init();
            log.info("Successfully build up socket connection with " + host
                    + ":" + port);
        } catch (Exception e) {
            log.error("",e);
            reconnect();
        }

    }

    /**
     * init this object, connect to the server indicated by serverHost and port
     * 
     * @throws Exception
     */
    private void init() throws Exception {
        InetSocketAddress endpoint = new InetSocketAddress(host, this.port);
        client = new Socket();
        client.setKeepAlive(true);
        client.setTcpNoDelay(true);
        client.connect(endpoint);

    }

    /**
     * reconnect to the server
     */
    public void reconnect() {
        boolean isConnected = false;
        while (!isConnected) {
            try {
                if (log.isDebugEnabled()) {
                    log.debug("SocketClient trying to reconnect to " + host
                            + ":" + port + "......");
                }
                if (reconCount++ == 10) { //  quit if it continuously failed
                    // to
                    // reconnect to peer for 10 times
                    log
                            .info("can not connect to peer for 10 times, BAM quit.");
                    SystemExit.exit("can not connect to " + host + ":" + port);
                }
                init();
                isConnected = true;
                reconCount = 0; // set to 0 once reconnection success.
                log.info("SocketClient successfully reconnected to " + host
                        + ":" + port);
            } catch (Exception e) {
                log.error("", e);
                try {
                    Thread.sleep(2 * 1000);
                } catch (InterruptedException e1) {
                    log.error("", e1);
                }
            }
        }
    }

	public Socket getClient() {
		return client;
	}

	public void setClient(Socket client) {
		this.client = client;
	}
    

}
